package com.hinnotek.amoeba.ui.activity.old

import android.os.Bundle
import android.view.View
import android.widget.*
import androidx.activity.viewModels
import com.lee.common.base.BaseActivity
import com.hinnotek.amoeba.R
import com.hinnotek.amoeba.databinding.ActivityAmountAllocatedBinding
import com.hinnotek.amoeba.dialog.CustomDialog
import com.hinnotek.amoeba.bean.old.AmountAllocatedBean
import com.hinnotek.amoeba.bean.old.CompanyContractNumBean
import com.hinnotek.amoeba.utilities.ClickUtil
import com.lee.common.utils.SharedPreUtils
import com.hinnotek.amoeba.utilities.ToastUtils
import com.hinnotek.amoeba.ext.initAdapter
import com.hinnotek.amoeba.viewmodels.PublicInterfaceViewModel
import com.lee.common.network.net.IStateObserver
import com.xuexiang.xutil.common.StringUtils
import dagger.hilt.android.AndroidEntryPoint
import java.util.*

@AndroidEntryPoint
class AmountAllocatedActivity : BaseActivity<ActivityAmountAllocatedBinding>(),
    View.OnClickListener {


    val viewModel by viewModels<PublicInterfaceViewModel>()


    private var data1: CompanyContractNumBean? = null
    private var orgId = 0
    private var customerId = 0
    private var amibaCustomerProjectId = 0
    private var companyContractId = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setLeftVisible(true)
        setContentView(R.layout.activity_amount_allocated)
        setTitle("合同金额分配")

    }

    override fun initVew() {

        bindingView.rbContractMoneyDistribution.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                bindingView.tv3.visibility = View.VISIBLE
                bindingView.tv2.visibility = View.GONE
                bindingView.tv4.visibility = View.GONE
            } else {
                bindingView.tv3.visibility = View.GONE
                bindingView.tv2.visibility = View.VISIBLE
                bindingView.tv4.visibility = View.VISIBLE
            }
        }
        bindingView.superButtonSubmit.setOnClickListener(this)
        setData()
    }

    override fun setData() {
        
        getSysOrgAmibaList()

        viewModel.companyContractiveData.observe(
            this,
            object : IStateObserver<MutableList<CompanyContractNumBean>>() {

                override fun onDataChange(data: MutableList<CompanyContractNumBean>) {
                    super.onDataChange(data)
                    bindingView.escContractNo.setOnItemClickListener { parent, view, position, id ->

                        data1 = data[position]
                        companyContractId = data[position].companyContractId

                        bindingView.llTv.visibility = View.VISIBLE
                        bindingView.tv1.visibility = View.VISIBLE
                        bindingView.tv1.text = "合同总金额:" + data1!!.signMoney
                        bindingView.tv2.text = "回款金额:" + data1!!.backMoney
                        bindingView.tv3.text = "剩余金额:" + data1!!.surplusMoney
                        bindingView.tv4.text = "未分金额:" + data1!!.backSurplusMoney
                        if (bindingView.rbContractMoneyDistribution.isChecked()) {
                            bindingView.tv3.visibility = View.VISIBLE
                            bindingView.tv2.visibility = View.GONE
                            bindingView.tv4.visibility = View.GONE
                        } else {
                            bindingView.tv3.visibility = View.GONE
                            bindingView.tv2.visibility = View.VISIBLE
                            bindingView.tv4.visibility = View.VISIBLE
                        }
                    }

                }

                override fun onReload(v: View?) {

                }

            })
    }

    /**
     * app端合同金额,回款金额分配接口
     */
    private fun addCompanyContractDistribution(
        orgId: Int, orgName: String, customerId: Int, customerName: String,
        amibaCustomerProjectId: Int, projectName: String, companyContractId: Int,
        contractNo: String, divideMoney: String
    ) {
        val customDialog = CustomDialog(mContext, "正在加载...")
        customDialog.show()

        val contractDistributionType =
            if (bindingView.rbContractMoneyDistribution.isChecked()) 1 else 2
        val createUser = SharedPreUtils.getString("userName")

        viewModel.addCompanyContractDistribution(
            contractDistributionType,
            orgId,
            orgName,
            customerId,
            customerName,
            amibaCustomerProjectId,
            projectName,
            companyContractId,
            contractNo,
            divideMoney,
            createUser
        ).observe(this, androidx.lifecycle.Observer {
            if (200 == it.code) {
                finishActivity()
            } else {
                customDialog.dismiss()
                ToastUtils.showShort(mContext, it.msg)
            }
        })

    }

    /**
     * app端获取全部阿米巴组织接口
     */
    private fun getSysOrgAmibaList() {

        val customDialog = CustomDialog(mContext, "正在加载...")
        customDialog.show()

        viewModel.getSysOrgAmibaList()
            .observe(this, object : IStateObserver<MutableList<AmountAllocatedBean>>() {
                override fun onDataChange(data: MutableList<AmountAllocatedBean>) {
                    val strings = arrayOfNulls<String>(data.size)
                    data.forEachIndexed { index, amountAllocatedBean ->
                        strings[index] = amountAllocatedBean.orgName
                    }
                    bindingView.escChooseAmoeba.initAdapter(strings)
                    bindingView.escChooseAmoeba.setOnItemClickListener { parent, view, position, id ->
                        orgId = data[position].orgId

                        viewModel.getAmibaCustomerListByOrgId(orgId)
                            .observe(this@AmountAllocatedActivity, androidx.lifecycle.Observer {

                            })
                        super.onDataChange(data)
                    }
                }

                override fun onError(e: Throwable?) {
                    ToastUtils.showShort(mContext, "网络异常，请稍候再试!")
                    customDialog.dismiss()
                    super.onError(e)
                }
                override fun onReload(v: View?) {}
            })
    }

    override fun onClick(v: View) {
        if (ClickUtil.isFastClick()) {
            return
        }
        when (v.id) {
            R.id.superButton_submit -> {
                val escChooseAmoeba = bindingView.escChooseAmoeba.editText.text.toString().trim()
                if (StringUtils.isEmpty(escChooseAmoeba)) {
                    ToastUtils.show(mContext, "请选择阿米巴")
                    return
                }
                val escChooseUser = bindingView.escChooseUser.editText.text.toString().trim()
                if (StringUtils.isEmpty(escChooseUser)) {
                    ToastUtils.show(mContext, "请选择客户")
                    return
                }
                val esc_choose_project_s = bindingView.escChooseProject.editText.text.toString().trim()
                if (StringUtils.isEmpty(esc_choose_project_s)) {
                    ToastUtils.show(mContext, "请选择项目")
                    return
                }
                val et_contract_no_s = bindingView.escContractNo.editText.getText().toString().trim()
                if (StringUtils.isEmpty(et_contract_no_s)) {
                    ToastUtils.show(mContext, "请选择合同编号")
                    return
                }
                val et_dividing_amount_s = bindingView.escChooseAmoeba.text.toString().trim()
                if (StringUtils.isEmpty(et_dividing_amount_s)) {
                    ToastUtils.show(mContext, "请填写划分金额")
                    return
                }
                if (bindingView.rbContractMoneyDistribution.isChecked) {
                    if (et_dividing_amount_s.toDouble() > data1!!.surplusMoney) {
                        ToastUtils.show(mContext, "剩余金额不足！")
                        return
                    }
                } else {
                    if (et_dividing_amount_s.toDouble() > data1!!.backSurplusMoney) {
                        ToastUtils.show(mContext, "未分金额不足！")
                        return
                    }
                }
                addCompanyContractDistribution(
                    orgId,
                    escChooseAmoeba,
                    customerId,
                    escChooseUser,
                    amibaCustomerProjectId,
                    esc_choose_project_s,
                    companyContractId,
                    et_contract_no_s,
                    et_dividing_amount_s
                )
            }
        }
    }


}